import os

def normalize_jar_path(path):
    """将路径标准化为JAR包规范的正斜杠路径"""
    # 替换系统分隔符为正斜杠
    normalized = path.replace(os.sep, '/')
    # 去除开头的./（避免路径差异）
    if normalized.startswith('./'):
        normalized = normalized[2:]
    # 合并连续斜杠
    while '//' in normalized:
        normalized = normalized.replace('//', '/')
    return normalized

def jar_path_to_system_path(jar_path, base_dir):
    """将JAR路径（正斜杠）转换为系统路径"""
    if not jar_path:
        return base_dir
    # 将正斜杠替换为系统分隔符
    system_path = jar_path.replace('/', os.sep)
    # 拼接基础目录
    return os.path.join(base_dir, system_path)

def guess_class_package_path_from_bytes(file_bytes, expected_class_name):
    """根据.class文件内容猜测包路径，返回类似 com/example/Foo.class 的相对路径

    说明：这里不完整解析class常量池，仅做启发式查找，将包含类名的UTF-8常量项
    中的全限定名提取出来作为包路径依据。
    """
    try:
        # 仅在前 128KB 内搜索以提升性能
        window = file_bytes[:131072]
        # 常见包名前缀关键词，提高命中率
        prefixes = [b'com/', b'org/', b'net/', b'cn/', b'io/', b'edu/', b'gov/', b'android/', b'java/', b'jakarta/']
        # 精确匹配带类名的路径（优先）
        needle = expected_class_name.encode('utf-8') + b'.class'
        start = window.find(needle)
        if start != -1:
            # 向前回溯找到最近的包分隔开始
            left = start
            while left > 0 and window[left - 1] not in (0, 10, 13, 9, 32):
                left -= 1
            segment = window[left:start]
            # 尝试在segment里找到最近的包前缀
            best = None
            for p in prefixes:
                idx = segment.rfind(p)
                if idx != -1:
                    candidate = segment[idx:] + needle
                    best = candidate
                    break
            if best:
                return best.decode('utf-8', errors='ignore')
        # 次优：搜索任何以已知前缀开始且包含类名的UTF-8片段
        for p in prefixes:
            idx = window.find(p)
            while idx != -1:
                end = min(idx + 512, len(window))
                frag = window[idx:end]
                if needle in frag:
                    # 从idx切到needle末尾
                    rel = frag.split(needle, 1)[0] + needle
                    return rel.decode('utf-8', errors='ignore')
                idx = window.find(p, idx + 1)
    except Exception:
        pass
    return None